/**
	Copyright (c) 2010 ATTi 
	All rights reserved.
	Author: Michael Shu
	Date: 5/25/2010
*/

trigger emailAttachmentReassigner on Attachment (before insert) {
	Set<ID> caseIDs = new Set<ID>();
	Set<ID> emailIDs = new Set<ID>();
    List<Attachment> attachments = new List<Attachment>();
    Set<ID> closedCCIRcaseIds = EmailSentFromCaseHelperClass.getClosedCCIRCaseIds(trigger.new);
    for( Attachment a : trigger.new ) {
        if( a.parentId == null )
            continue;
        
        String tPrefix = String.Valueof(a.parentId).subString(0,3);
        if(tPrefix == EmailSentFromCaseHelperClass.Case_Prefix){
        	if(!closedCCIRcaseIds.contains(a.parentId)){
        		caseIDs.add(a.parentId);
        	}else{
        		a.addError('You do not have permission to add attachment(s) to this closed case.');
        	}
        }else if( tPrefix == EmailSentFromCaseHelperClass.EmailMessage_Prefix){
        	emailIDs.add(a.parentId);
        	attachments.add(a);
        }
    }
    if(!emailIDs.isEmpty()){
    	List<EmailMessage> emails = [select parentID from EmailMessage where Id IN: emailIDs];
    	Map<ID, ID> mapEmailCase = new Map<ID, ID>();
    	for(EmailMessage e : emails){
    		mapEmailCase.put(e.Id, e.parentID);
    	}
    	for(Attachment a : attachments){
    		a.parentId = mapEmailCase.get(a.parentId);
    	}
    }
    
    if(!caseIDs.isEmpty()){
    	EmailSentFromCaseHelperClass.sendEmailtoCaseOwnerIfDifferent(caseIDs, 'New Attachment');
    }
}